<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 300px">
      <el-breadcrumb-item style="font-size: 16px">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px">专业管理</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px"
        >推荐专业管理</el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="search">
      <el-input
        style="width: 200px"
        placeholder="请输入专业名称"
        v-model="majorName"
        @blur="getUniList_Token"
      ></el-input>
      <el-button @click="searchMajor" type="primary" icon="el-icon-search"
        >搜索</el-button
      >
    </div>
    <el-table
      :data="userData"
      border
      style="
        width: 1001px;
        margin-left:35px
        position: relative;
      "
      :header-cell-style="headClass"
    >
      <el-table-column label="序号" width="100" type="index" align="center">
      </el-table-column>
      <el-table-column label="专业名称" width="250" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专业层次" width="180" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专业门类" width="220" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state"></el-switch>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="showEdit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.name)"
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeUserById(scope.row.name)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="修改信息"
      :visible.sync="editDialogVisible"
      width="400px"
      @close="editDialogClosed"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="专业名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
          <!-- <span v-if="nameIsRight === 0">{{ nameMsg }}</span> -->
        </el-form-item>
        <el-form-item label="专业层次" prop="category">
          <el-input v-model="editForm.category" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="专业门类" prop="type">
          <el-input v-model="editForm.type" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      layout="total, prev, pager, next"
      :total="queryInfo.count"
      background
    >
      <!--
        @current-change(页码发生改变时触发)
        :current-page(设置当前页码)
        :page-size(设置每页的数据条数)
        :total(设置总页数)
     -->
    </el-pagination>
  </el-card>
</template>

<script>
import qs from "qs";
import throttling from "@/public/throttling.js";
export default {
  data() {
    var validateName = (rule, value, callback) => {
      // 只能输入汉字
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("专业名称不能为空!"));
      } else {
        if (!reg.test(value)) {
          console.log("输入不合法");
          callback(new Error("只能输入汉字！"));
        } else {
          // console.log("输入合法");
          // console.log(typeof value);
          callback();
        }
      }
    };
    var validateCategory = (rule, value, callback) => {
      // 只能输入汉字
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("专业层次不能为空!"));
      } else {
        if (!reg.test(value)) {
          console.log("输入不合法");
          callback(new Error("只能输入汉字！"));
        } else if (value.search("科") === -1) {
          callback(new Error("填写格式为xx科!"));
        } else {
          // console.log("输入合法");
          // console.log(typeof value);
          callback();
        }
      }
    };
    var validateType = (rule, value, callback) => {
      // 只能输入汉字
      let reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("专业门类不能为空!"));
      } else {
        if (!reg.test(value)) {
          console.log("输入不合法");
          callback(new Error("只能输入汉字！"));
        } else if (value.search("学") === -1) {
          callback(new Error("填写格式为xx学!"));
        } else {
          // console.log("输入合法");
          // console.log(typeof value);
          callback();
        }
      }
    };
    return {
      // 正确性验证
      nameIsRight: 0,
      nameMsg: "",
      // 搜索
      majorName: "",
      // 按钮
      showEdit: true,
      showRemove: true,
      // 控制修改院校
      editDialogVisible: false,
      // 修改用户的表单数据
      editForm: {
        fname: "",
        name: "",
        category: "",
        type: "",
      },
      // 属性
      editFormRules: {
        name: [{ validator: validateName, trigger: "blur" }],
        // 专业层次
        category: [{ validator: validateCategory, trigger: "blur" }],
        // 专业门类
        type: [{ validator: validateType, trigger: "blur" }],
      },
      //初始分页条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 6,
        count: 0,
      },
      // 保存请求回来的用户列表数据
      userData: [
        {
          // order: 1,
          name: "软件工程",
          category: "本科",
          type: "工学",
        },
        {
          // order: 1,
          name: "软件工程",
          category: "本科",
          type: "工学",
        },
      ],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    // 表格表头
    headClass() {
      //表头居中显示
      return "color:rgba(255,101,0);font-weight:bold;font-size:16px";
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCurrentChange: throttling(function (page) {
      this.queryInfo.pagenum = page;
      console.log("跳转了");
      // 重新按照pagenum发送请求 请求最新的数据
      this.getUniList_Token();
    }, 1000),
    cancel() {
      this.editDialogVisible = false;
      this.$message("取消修改");
    },
    getUniList_Token() {
      const token = window.sessionStorage.getItem("tokenvalue");
      this.$axios.defaults.headers.common["satoken"] = token;
      this.$axios
        .get("/back/majors", {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.status === 666) {
            this.$message.error("请先登录");
            this.$router.replace("/login");
          } else {
            this.$message.success("获取推荐专业列表成功！");
            this.userData = res.data.data;
            this.queryInfo.count = res.data.code;
          }
        });
    },
    showEditDialog(name) {
      //   //将获取到的数据保存到数据editForm中
      this.editForm.fname = name;
      //显示弹出窗
      this.editDialogVisible = true;
      // });
    },
    editDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.editFormRef.resetFields();
    },
    editUser: throttling(function () {
      // 用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        else {
          const token = window.sessionStorage.getItem("tokenvalue");
          this.$axios.defaults.headers.common["satoken"] = token;
          // 发送请求 完成修改用户的操作
          this.$axios
            .put(
              "/back/major",
              qs.stringify({
                fName: this.editForm.fname,
                name: this.editForm.name,
                category: this.editForm.category,
                type: this.editForm.type,
              })
            )
            .then((res) => {
              //修改成功的提示
              this.$message.success("修改专业成功");
              //关闭对话框
              this.editDialogVisible = false;
              //重新请求最新的数据
              this.getUniList_Token();
            });
        }
      });
    }, 1000),
    removeUserById(name) {
      //弹出确定取消框，是否删除用户
      this.$confirm("请问是否要永久删除该专业", "删除提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
      })
        .then(() => {
          //发送请求根据id完成删除操作
          this.$axios;
          this.$axios.delete("/back/major/" + name).then((res) => {
            //修改成功的提示
            this.$message.success("删除专业成功");
            //重新请求最新的数据
            this.getUniList_Token();
          });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消删除" : "放弃删除",
          });
        });
    },
    searchMajor: throttling(function () {
      this.$axios
        .get("/back/major/" + this.majorName, {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          this.userData = res.data.data;
          this.queryInfo.count = res.data.code;
        });
    }, 1000),
  },
  created() {
    this.$axios.get("/back/major/updateButton").then((res) => {
      if (res.data.code === 500) {
        this.showEdit = false;
      }
    });
    this.$axios.get("/back/major/deleteButton").then((res) => {
      if (res.data.code === 500) {
        this.showRemove = false;
      }
    });
    this.getUniList_Token();
  },
};
</script>

<style scoped>
.box-card {
  position: relative;
  margin: 22px auto;
  min-height: 550px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.search {
  margin-top: 20px;
  margin-left: 40px;
}

.el-table {
  margin-top: 20px;
}

.el-dialog .el-dialog__body {
  padding: 10px 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.pagination {
  position: absolute;
  bottom: 10px;
  width: 412px;
  left: 50%;
  margin-left: -206px;
}
</style>